package com.zhida.jiyangcenter.buycar

import android.os.Bundle
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.ShopCarListEntity
import com.zhida.jiyangcenter.api.ShopCarStoreListEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.order.ConfirmOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import kotlinx.android.synthetic.main.activity_buy_car.*

@TitleBar(false)
@ContentLayout(R.layout.activity_buy_car)
class BuyCarActivity : BaseActivity() {
    val adapter = Adapter()
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.title("购物车")
        rv_buy_car.layoutManager = LinearLayoutManager(context)
        rv_buy_car.adapter = adapter
        rv_buy_car.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context)
                .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
        )
        adapter.setIsAllListener {
            check_box.setChecked(it, true)
            if (it) {

                adapter.notifyDataSetChanged()
            }
        }
        adapter.setAddListener { i, i2 ->
            var num = adapter.data[i2].serve?.get(i)?.num?:1
            num++
            lifecycleScope.request({
                APIShop.service().shopcarServeEdit(adapter.data[i2]?.serve?.get(i)?.car_uuid?:"", num)
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    adapter.data[i2].serve?.get(i)!!.num++
                    adapter.notifyItemChanged(i2)
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }
        adapter.setReduceListener { i, i2 ->
            var num = adapter.data[i2].serve?.get(i)?.num?:1
            if (num > 1) {
                num--
                lifecycleScope.request({
                    APIShop.service()
                        .shopcarServeEdit(adapter.data[i2].serve?.get(i)?.car_uuid?:"", num)
                }, object : BaseAPI<Any>() {
                    override fun onSuccess(t: Any?, state: Int, msg: String) {
                        adapter.data[i2].serve?.get(i)!!.num--
                        adapter.notifyItemChanged(i2)
                    }

                    override fun onError(e: APIException) {
                        tipFail(e.eMessage)
                    }

                })
            } else {
                toast("太少了，不能再减了")
            }
        }
        adapter.setDeleteListener { i, i2, adapters ->
            lifecycleScope.request({
                APIShop.service().shopcarServeDel(adapter.data[i2].serve?.get(i)?.car_uuid?:"")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    adapters.remove(i)
                    adapters.notifyDataSetChanged()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }

        check_box.setOnClickListener {
            check_box.setChecked(!check_box.isChecked, true)
            adapter.notifyDataSetChanged()
        }
        tv_buy_car_settlement.setOnClickListener {
            startActivity<ConfirmOrderActivity> { }
        }
    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    private fun getData() {
        lifecycleScope.request({ APIShop.service().shopcarServeList() },
            object : BaseAPI<ShopCarStoreListEntity>() {
                override fun onSuccess(t: ShopCarStoreListEntity?, state: Int, msg: String) {
                    adapter.setNewData(t?.shop_car)
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    class Adapter :
        BaseQuickAdapter<ShopCarStoreListEntity.ShopCar, BaseViewHolder>(R.layout.item_buy_car) {
        val positionMap = HashMap<Int, ArrayList<Int>>()
        var isAllListener: ((Boolean) -> Unit)? = null
        fun setIsAllListener(isAllListener: ((Boolean) -> Unit)) {
            this.isAllListener = isAllListener
        }

        private var addListener: ((Int, Int) -> Unit)? = null
        private var reduceListener: ((Int, Int) -> Unit)? = null
        private var deleteListener: ((Int, Int, ItemAdapter) -> Unit)? = null
        fun setAddListener(addListener: ((Int, Int) -> Unit)) {
            this.addListener = addListener
        }

        fun setReduceListener(reduceListener: ((Int, Int) -> Unit)) {
            this.reduceListener = reduceListener
        }

        fun setDeleteListener(deleteListener: ((Int, Int, ItemAdapter) -> Unit)) {
            this.deleteListener = deleteListener
        }

        override fun convert(helper: BaseViewHolder, item: ShopCarStoreListEntity.ShopCar?) {
            val rv_buy_car = helper.getView<SwipeRecyclerView>(R.id.rv_buy_car)
            val scb_buy_car = helper.getView<SmoothCheckBox>(R.id.scb_buy_car)
            helper.setText(R.id.tv_buy_car_name, item?.store?.name)
            val adapter = ItemAdapter()
            rv_buy_car.layoutManager = object : LinearLayoutManager(mContext) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            helper.addOnClickListener(R.id.tv_buy_car_name)
            if (rv_buy_car.adapter == null) {
                rv_buy_car.setSwipeMenuCreator { leftMenu, rightMenu, position ->
                    rightMenu.addMenuItem(SwipeMenuItem(mContext).apply {
                        setBackgroundColorResource(R.color.color_333333)
                        setTextColorResource(R.color.colorPrimary)
                        text = "删除"
                        width = dp2px(70f)
                        height = ViewGroup.LayoutParams.MATCH_PARENT
                    })
                }
                rv_buy_car.setOnItemMenuClickListener { menuBridge, adapterPosition ->
                    menuBridge.closeMenu()
                    deleteListener?.invoke(
                        adapterPosition,
                        helper.layoutPosition - headerLayoutCount,
                        adapter
                    )
                }
            }
            rv_buy_car.addItemDecoration(
                HorizontalDividerItemDecoration.Builder(mContext)
                    .sizeResId(R.dimen.dividerSmall).colorResId(R.color.colorBack).build()
            )

            adapter.setOnItemChildClickListener { _, view, position ->
                when (view.id) {
                    R.id.scb_item_buy_car -> {
                        if (adapter.indexList.contains(position)) {
                            adapter.indexList.remove(position)
                        } else {
                            adapter.indexList.add(position)
                        }
                        scb_buy_car.setChecked(
                            adapter.indexList.size == adapter.data.size,
                            true
                        )
                        positionMap[helper.layoutPosition - headerLayoutCount] = adapter.indexList
                        adapter.notifyDataSetChanged()
                    }
                }
            }
            rv_buy_car.adapter = adapter
            adapter.setNewData(item?.serve)
            adapter.setOnItemChildClickListener { _, view, position ->
                when (view.id) {
                    R.id.tv_item_buy_car_add -> {
                        addListener?.invoke(position, helper.layoutPosition - headerLayoutCount)
                    }
                    R.id.tv_item_buy_car_reduce -> {
                        reduceListener?.invoke(position, helper.layoutPosition - headerLayoutCount)
                    }
                }
            }
            scb_buy_car.setOnClickListener {
                scb_buy_car.setChecked(!scb_buy_car.isChecked, true)
                if (scb_buy_car.isChecked) {
                    adapter.data.forEachIndexed { index, s ->
                        adapter.indexList.add(index)
                    }
                    positionMap[helper.layoutPosition - headerLayoutCount] = adapter.indexList
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.indexList.clear()
                    positionMap[helper.layoutPosition - headerLayoutCount] = adapter.indexList
                    positionMap.remove(helper.layoutPosition - headerLayoutCount)
                    adapter.notifyDataSetChanged()
                }
            }
            scb_buy_car.setChecked(
                positionMap.containsKey(helper.layoutPosition - headerLayoutCount) && positionMap[helper.layoutPosition - headerLayoutCount]!!.size == adapter.data.size,
                true
            )
        }

        class ItemAdapter :
            BaseQuickAdapter<ShopCarStoreListEntity.ShopCar.Serve, BaseViewHolder>(R.layout.item_item_buy_car) {
            val indexList = ArrayList<Int>()
            override fun convert(
                helper: BaseViewHolder,
                item: ShopCarStoreListEntity.ShopCar.Serve?
            ) {
                glideImage(helper.getView(R.id.niv_item_buy_car), item?.picture ?: "")
                helper.setText(R.id.tv_item_buy_car_name, item?.name)
                    .setText(R.id.tv_item_buy_car_money, "￥${item?.max_money}")
                    .setText(R.id.tv_item_buy_car_num, item?.num.toString())
                    .addOnClickListener(R.id.tv_item_buy_car_add)
                    .addOnClickListener(R.id.tv_item_buy_car_reduce)
                val scb_item_buy_car = helper.getView<SmoothCheckBox>(R.id.scb_item_buy_car)
                scb_item_buy_car.setChecked(
                    indexList.contains(helper.layoutPosition - headerLayoutCount),
                    true
                )
                helper.addOnClickListener(R.id.scb_item_buy_car)
            }

        }
    }
}